import { configByID, gameConfig, gameConfigHandle } from "js/config/gameConfig"
import Random from "js/core/random"
import utils from "js/core/utils"
import { FighterAttriModel, FighterModel } from "js/model/fighterModel"
import { EquipmentItemModel, ItemModel, TreasureItemModel } from "js/model/itemModel"
import { PartnerModel } from "js/model/partnerModel"
import { PlayerModel } from "js/model/playerModel"
import { CreateKind, EquipmentItemType, TownBuildType } from "js/typeDefine/typeDefine"
import bagHandle from "./bagHandle"
import itemHandle from "./itemHandle"
import playerHandle from "./playerHandle"

class EquipmentHandle {
    wuxingPartList = ['hand', 'head', 'body', 'foot', 'neck']
    equipmentKindToPart = {
        [EquipmentItemType.Hand]: 'hand',
        [EquipmentItemType.Head]: 'head',
        [EquipmentItemType.Body]: 'body',
        [EquipmentItemType.Foot]: 'foot',
        [EquipmentItemType.Neck]: 'neck',
        [EquipmentItemType.Wrist]: 'wrist',
        [EquipmentItemType.Finger]: 'finger',
        [EquipmentItemType.Cloak]: 'cloak',
        [EquipmentItemType.Waist]: 'waist',
        [EquipmentItemType.Palm]: 'palm',
        [EquipmentItemType.SubHand]: 'subHand',
    }
    equipmentPartToKind = {
        'hand': EquipmentItemType.Hand,
        'head': EquipmentItemType.Head,
        'body': EquipmentItemType.Body,
        'foot': EquipmentItemType.Foot,
        'neck': EquipmentItemType.Neck,
        'wrist': EquipmentItemType.Wrist,
        'finger': EquipmentItemType.Finger,
        'cloak': EquipmentItemType.Cloak,
        'waist': EquipmentItemType.Waist,
        'palm': EquipmentItemType.Palm,
        'subHand': EquipmentItemType.SubHand,
    }

    //获得随机装备tID
    getRandomEquipmentID(rand: Random): number {
        let weaponList = gameConfigHandle.gameConfig.base.weaponList
        let shoeList = gameConfigHandle.gameConfig.base.shoeList
        let otherEquipmentList = gameConfigHandle.gameConfig.base.otherEquipmentList
        let dropEquipments = otherEquipmentList.concat([utils.getOneFromArray(weaponList, rand), utils.getOneFromArray(shoeList, rand)])
        let rate = rand.intn(100)
        if (rate <= 20) {
            return utils.getOneFromArray(weaponList, rand)
        } else {
            return utils.getOneFromArray(dropEquipments, rand)
        }
    }

    //判断是否有装备可以穿上
    haveEquipmentToPutOn(player: PlayerModel) {
        for (let i = 0; i < player.teamList.list.length; i++) {
            let p = player.teamList.list[i]
            if (p) {
                let equipments = Object.entries(p.equipments[p.equipmentActive])
                let equipmentsInBag = player.equipmentBag.items
                for (let i = 0; i < equipments.length; i++) {
                    if (!equipments[i][1]) {
                        for (let j = 0; j < equipmentsInBag.length; j++) {
                            if (equipmentsInBag[j]) {
                                let equipmentKind = gameConfigHandle.configByID[equipmentsInBag[j].tID].equipmentKind
                                if (equipmentKind == equipmentHandle.equipmentPartToKind[equipments[i][0]]) {
                                    return true
                                }
                            }
                        }
                    }
                }
            }

        }
        return false
    }

    //根据物品id 等级 创建模式生成随机属性的装备
    create(player: PlayerModel, id: number, lvl: number, rand: Random, quality: number, creatKind: number = 0, subAttriNames?: string[], skillID?: null) {
        id = id ? id : this.getRandomEquipmentID(rand)
        let pLvl = 0
        player.teamList.list.forEach(p => {
            if (p && p.lvl > pLvl) {
                pLvl = p.lvl
            }
        })
        if (lvl > pLvl) {
            lvl = pLvl
        }
        creatKind = creatKind || 0  //默认为普通地图掉落模式
        let equipmentItemConfig = gameConfigHandle.configByID[id]
        let partnerConfig = gameConfigHandle.gameConfig.partner
        let attriNames = equipmentItemConfig.attri
        let equipmentItem = new EquipmentItemModel()
        let coe = gameConfigHandle.gameConfig.map.coe
        if (quality == null || quality == undefined) {
            //普通地图
            if (creatKind == 0) {
                let qualityDropNormal = gameConfigHandle.gameConfig.map.qualityDropNormal
                quality = utils.getRandomValue(qualityDropNormal, coe, rand)
            }
            //精英地图
            else if (creatKind == 1) {
                let qualityDropElite = gameConfigHandle.gameConfig.map.qualityDropElite
                quality = utils.getRandomValue(qualityDropElite, coe, rand)
            }
        }
        equipmentItem.quality = quality
        //根据品级生成主属性值
        let qualityUp = gameConfigHandle.gameConfig.equipment.qualityUp
        let mainAttriConfig = gameConfigHandle.gameConfig.equipment.mainAttri
        let valueRandomRange = gameConfigHandle.gameConfig.equipment.valueRandomRange
        //从可出现属性数组中选择一个属性生成装备主属性
        let attriName: string = utils.getOneFromArray(attriNames, rand)
        let attriValue = utils.getIncValue(partnerConfig.attriList[attriName], lvl * mainAttriConfig[attriName][0]) * mainAttriConfig[attriName][1] * ((equipmentItem.quality - 1) * qualityUp + 1)
        if (equipmentItemConfig.attriCoe) {
            attriValue = attriValue * equipmentItemConfig.attriCoe
        }

        let max = utils.getValueByAttri(attriValue, attriName)
        let min, minRange
        if (CreateKind.Boss == creatKind) {
            min = max
            minRange = valueRandomRange[1]
        } else {
            minRange = valueRandomRange[0]
            min = utils.getValueByAttri(attriValue * minRange / 100, attriName)
        }
        attriValue = utils.addRandomByPer(attriValue, minRange, rand, 'float')
        attriValue = utils.getValueByAttri(attriValue, attriName)
        if (attriValue < 0.1) {
            attriValue = 0.1
        }
        equipmentItem.mainAttris.push([attriName, attriValue, min, max])

        //固定属性
        let fixedAttri = equipmentItemConfig.fixedAttri
        if (fixedAttri) {
            equipmentItem.fixedAttri = []
            fixedAttri.forEach(item => {
                let attriName = item.name

                if (item.value) {
                    let value = item.value
                    equipmentItem.fixedAttri.push([attriName, value])
                } else if (item.values) {
                    let value = utils.getIncValue(item.values, lvl)
                    equipmentItem.fixedAttri.push([attriName, value])
                }

            })
        }
        equipmentItem.strengthen = 0
        equipmentItem.lvl = lvl
        equipmentItem.subAttris = this.createSubAttri(id, equipmentItem.quality, lvl, rand, skillID)
        let item = itemHandle.create({ tID: id }, rand)
        item.equipment = equipmentItem
        return item
    }

    //根据物品id 等级 创建模式生成随机属性的装备
    createForFantasy(player: PlayerModel, id: number, lvl: number, rand: Random, quality: number, creatKind: number = 0, skillID?: null) {
        id = id ? id : this.getRandomEquipmentID(rand)
        creatKind = creatKind || 0  //默认为普通地图掉落模式
        let equipmentItemConfig = gameConfigHandle.configByID[id]
        let partnerConfig = gameConfigHandle.gameConfig.partner
        let attriNames = equipmentItemConfig.attri
        let equipmentItem = new EquipmentItemModel()
        let coe = gameConfigHandle.gameConfig.map.coe
        if (quality == null || quality == undefined) {
            let qualityDropNormal = gameConfigHandle.gameConfig.map.qualityDropNormal
            quality = utils.getRandomValue(qualityDropNormal, coe, rand)
        }
        equipmentItem.quality = quality
        //根据品级生成主属性值
        let qualityUp = gameConfigHandle.gameConfig.equipment.qualityUp
        let mainAttriConfig = gameConfigHandle.gameConfig.equipment.mainAttri
        let valueRandomRange = gameConfigHandle.gameConfig.equipment.valueRandomRange
        //从可出现属性数组中选择一个属性生成装备主属性
        let attriName: string = utils.getOneFromArray(attriNames, rand)
        let attriValue = utils.getIncValue(partnerConfig.attriList[attriName], lvl * mainAttriConfig[attriName][0]) * mainAttriConfig[attriName][1] * ((equipmentItem.quality - 1) * qualityUp + 1) * 0.5
        if (equipmentItemConfig.attriCoe) {
            attriValue = attriValue * equipmentItemConfig.attriCoe
        }

        let max = utils.getValueByAttri(attriValue, attriName)
        let min, minRange
        if (CreateKind.Boss == creatKind) {
            min = max
            minRange = valueRandomRange[1]
        } else {
            minRange = valueRandomRange[0]
            min = utils.getValueByAttri(attriValue * minRange / 100, attriName) * 0.5
        }
        attriValue = utils.addRandomByPer(attriValue, minRange, rand, 'float')
        attriValue = utils.getValueByAttri(attriValue, attriName)
        if (attriValue < 0.1) {
            attriValue = 0.1
        }
        equipmentItem.mainAttris.push([attriName, attriValue, min, max])

        //固定属性
        let fixedAttri = equipmentItemConfig.fixedAttri
        if (fixedAttri) {
            equipmentItem.fixedAttri = []
            fixedAttri.forEach(item => {
                let attriName = item.name

                if (item.value) {
                    let value = item.value
                    equipmentItem.fixedAttri.push([attriName, value])
                } else if (item.values) {
                    let value
                    if (utils.getPerByAttri(attriName) == '%') {
                        value = Math.floor(utils.getIncValue(item.values, lvl) * 0.25)
                    } else {
                        value = Math.floor(utils.getIncValue(item.values, lvl) * 0.2)
                    }
                    value = value < 1 ? 1 : value
                    equipmentItem.fixedAttri.push([attriName, value])
                }

            })
        }
        equipmentItem.strengthen = 0
        equipmentItem.lvl = lvl
        equipmentItem.subAttris = this.createSubAttriForFantasy(id, equipmentItem.quality, lvl, rand, skillID ? [skillID] : [])
        let item = itemHandle.create({ tID: id }, rand)
        item.equipment = equipmentItem
        return item
    }

    //随机属性生成
    createSubAttriForFantasy(tid, quality: number, lvl: number, rand: Random, pSkillID?: number[]) {
        let itemConfig = gameConfigHandle.configByID[tid]
        let subAttris = []
        let equipmentConfig = gameConfigHandle.gameConfig.equipment
        let subAttriConfig = equipmentConfig.subAttriInfo
        let amount = subAttriConfig.subAttriAmountByQuality[quality - 1]
        let list = []
        if (pSkillID && pSkillID.length > 0) {
            // 待实现
        } else {
            if (itemConfig.equipmentKind != EquipmentItemType.Hand && itemConfig.equipmentKind != EquipmentItemType.SubHand) {
                list = utils.getRandomArrayNoRepeat(subAttriConfig.fantasyDefList, amount, rand)
            } else {
                list = utils.getRandomArrayNoRepeat(subAttriConfig.fantasyList, amount, rand)
            }
        }
        let subAttriList: string[] = []
        for (let i = 0; i < subAttriConfig.subAttriList.length; i++) {
            subAttriList.push(subAttriConfig.subAttriList[i])
        }
        list.forEach((attriType, i) => {
            if (attriType == 'attri') {
                let attriName = utils.getOneFromArray(subAttriList, rand)
                //去掉已经出现的属性,避免出现重复的属性
                subAttriList.splice(subAttriList.indexOf(attriName), 1)

                //百分比属性
                if (attriName == 'crit' || attriName == 'critHurt' || attriName == 'hit' || attriName == 'dodge') {
                    let minValue = subAttriConfig.subAttriValue2[attriName][0] + subAttriConfig.subAttriValue2[attriName][2] * quality
                    let maxValue = subAttriConfig.subAttriValue2[attriName][1] + subAttriConfig.subAttriValue2[attriName][2] * quality
                    let value = utils.getRandomNumber(Math.floor(minValue * 10), Math.floor(maxValue * 10), rand) / 10
                    subAttris.push([attriType, attriName, value])
                } else {
                    let upValues = gameConfigHandle.gameConfig.partner.attriList[attriName]
                    let values = subAttriConfig.subAttriValue[attriName]
                    let value = utils.getIncValue(upValues, lvl * values[0]) * values[1] * 0.2
                    let valueRandomRange = gameConfigHandle.gameConfig.equipment.valueRandomRange
                    value = utils.addRandomByPer(value, valueRandomRange[0], rand, 'float')
                    value = utils.getValueByAttri(value, attriName)
                    subAttris.push([attriType, attriName, value])
                }
            } else if (attriType == 'reduceSkillCd') {
                let skillID = null
                if (itemConfig.targets) {
                    let pID: any = utils.getOneFromArray(itemConfig.targets, rand)
                    if (pID) {
                        let partnerConfig = gameConfigHandle.configByID[pID]
                        skillID = partnerConfig.skills[0]
                    }
                }
                if (skillID) {
                    let minValue = subAttriConfig.reduceSkillCd[0] + subAttriConfig.reduceSkillCd[2] * quality
                    let maxValue = subAttriConfig.reduceSkillCd[1] + subAttriConfig.reduceSkillCd[2] * quality
                    let value = utils.getRandomNumber(Math.floor(minValue * 10), Math.floor(maxValue * 10), rand) / 10
                    subAttris.push([attriType, skillID, value])
                }
            }
            else if (attriType == 'addSkillHurt') {
                let skillID
                if (itemConfig.targets) {
                    let pID: any = utils.getOneFromArray(itemConfig.targets, rand)
                    if (pID) {
                        let partnerConfig = gameConfigHandle.configByID[pID]
                        skillID = partnerConfig.skills[0]
                    }
                } else {
                    skillID = utils.getOneFromArray(gameConfigHandle.gameConfig.base.attackSkillList, rand)
                }
                let minValue = subAttriConfig.addSkillHurt[0] + subAttriConfig.addSkillHurt[2] * quality
                let maxValue = subAttriConfig.addSkillHurt[1] + subAttriConfig.addSkillHurt[2] * quality
                let value = utils.getRandomNumber(minValue, maxValue, rand)
                subAttris.push([attriType, skillID, value])
            }
            else if (typeof attriType == 'string') {
                let minValue = subAttriConfig[attriType][0] + subAttriConfig[attriType][2] * quality
                let maxValue = subAttriConfig[attriType][1] + subAttriConfig[attriType][2] * quality
                let value = utils.getRandomNumber(minValue, maxValue, rand)
                subAttris.push([attriType, value])
            }
        })
        return subAttris
    }

    //随机属性生成
    createSubAttri(tid, quality: number, lvl: number, rand: Random, pSkillID?) {
        let itemConfig = gameConfigHandle.configByID[tid]
        let subAttris = []
        let equipmentConfig = gameConfigHandle.gameConfig.equipment
        let subAttriConfig = equipmentConfig.subAttriInfo
        let amount = subAttriConfig.subAttriAmountByQuality[quality - 1]
        let list = []
        if (pSkillID) {
            let attriAmount = amount - 1
            let attriList = subAttriConfig.list
            if (quality == 6) {
                attriAmount -= 1
                attriList = attriList.filter(l => l != 'addSkillHurt')
                let minValue = subAttriConfig.addSkillHurt[0] + subAttriConfig.addSkillHurt[2] * quality
                let maxValue = subAttriConfig.addSkillHurt[1] + subAttriConfig.addSkillHurt[2] * quality
                let value = utils.getRandomNumber(minValue, maxValue, rand)
                subAttris.push(['addSkillHurt', pSkillID, value])
            }
            let skillList = attriList.filter(l => l != 'reduceSkillCd')
            list = utils.getRandomArrayNoRepeat(skillList, attriAmount <= 0 ? 0 : attriAmount, rand)

            let minValue = subAttriConfig.reduceSkillCd[0] + subAttriConfig.reduceSkillCd[2] * quality
            let maxValue = subAttriConfig.reduceSkillCd[1] + subAttriConfig.reduceSkillCd[2] * quality
            let value = utils.getRandomNumber(Math.floor(minValue * 10), Math.floor(maxValue * 10), rand) / 10
            subAttris.push(['reduceSkillCd', pSkillID, value])
        } else {
            if (itemConfig.equipmentKind != EquipmentItemType.Hand && itemConfig.equipmentKind != EquipmentItemType.SubHand) {
                list = subAttriConfig.list.filter(l => l != 'reduceSkillCd')
            } else {
                list = utils.getRandomArrayNoRepeat(subAttriConfig.list, amount, rand)
            }
        }
        let subAttriList: string[] = []
        for (let i = 0; i < subAttriConfig.subAttriList.length; i++) {
            subAttriList.push(subAttriConfig.subAttriList[i])
        }
        list.forEach((attriType, i) => {
            if (attriType == 'attri') {
                let attriName = utils.getOneFromArray(subAttriList, rand)
                //去掉已经出现的属性,避免出现重复的属性
                subAttriList.splice(subAttriList.indexOf(attriName), 1)

                //百分比属性
                if (attriName == 'crit' || attriName == 'critHurt' || attriName == 'hit' || attriName == 'dodge') {
                    let minValue = subAttriConfig.subAttriValue2[attriName][0] + subAttriConfig.subAttriValue2[attriName][2] * quality
                    let maxValue = subAttriConfig.subAttriValue2[attriName][1] + subAttriConfig.subAttriValue2[attriName][2] * quality
                    let value = utils.getRandomNumber(Math.floor(minValue * 10), Math.floor(maxValue * 10), rand) / 10
                    subAttris.push([attriType, attriName, value])
                } else {
                    let upValues = gameConfigHandle.gameConfig.partner.attriList[attriName]
                    let values = subAttriConfig.subAttriValue[attriName]
                    let value = utils.getIncValue(upValues, lvl * values[0]) * values[1]
                    let valueRandomRange = gameConfigHandle.gameConfig.equipment.valueRandomRange
                    value = utils.addRandomByPer(value, valueRandomRange[0], rand, 'float')
                    value = utils.getValueByAttri(value, attriName)
                    subAttris.push([attriType, attriName, value])
                }
            } else if (attriType == 'reduceSkillCd') {
                let skillID = null
                if (itemConfig.targets) {
                    let pID: any = utils.getOneFromArray(itemConfig.targets, rand)
                    if (pID) {
                        let partnerConfig = gameConfigHandle.configByID[pID]
                        skillID = partnerConfig.skills[0]
                    }
                }
                if (skillID) {
                    let minValue = subAttriConfig.reduceSkillCd[0] + subAttriConfig.reduceSkillCd[2] * quality
                    let maxValue = subAttriConfig.reduceSkillCd[1] + subAttriConfig.reduceSkillCd[2] * quality
                    let value = utils.getRandomNumber(Math.floor(minValue * 10), Math.floor(maxValue * 10), rand) / 10
                    subAttris.push([attriType, skillID, value])
                }
            }
            else if (attriType == 'addSkillHurt') {
                let skillID
                if (itemConfig.targets) {
                    let pID: any = utils.getOneFromArray(itemConfig.targets, rand)
                    if (pID) {
                        let partnerConfig = gameConfigHandle.configByID[pID]
                        skillID = partnerConfig.skills[0]
                    }
                } else {
                    skillID = utils.getOneFromArray(gameConfigHandle.gameConfig.base.attackSkillList, rand)
                }
                let minValue = subAttriConfig.addSkillHurt[0] + subAttriConfig.addSkillHurt[2] * quality
                let maxValue = subAttriConfig.addSkillHurt[1] + subAttriConfig.addSkillHurt[2] * quality
                let value = utils.getRandomNumber(minValue, maxValue, rand)
                subAttris.push([attriType, skillID, value])
            }
        })
        return subAttris
    }

    townCreate(player: PlayerModel, data: any, rand) {
        let item: ItemModel = null
        let { makeItemLvl, makeItemKind, useItemStatus, baseMake, time } = data
        let lvl = player.townInfo.subBuildLvl[TownBuildType.Make] || 0
        if (baseMake) {
            // 普通打造
            let max = 0, qualityRate = {}
            let baseMakeQuality = gameConfig.town.makeConfig.baseMakeQuality
            Object.entries(baseMakeQuality).forEach(bmq => {
                let quaility = bmq[0]
                let rateValues = bmq[1] || [0, 0]
                let rate = utils.getIncValue(rateValues, lvl, true)
                max += rate
                qualityRate[quaility] = rate
            })

            let entries = Object.entries(qualityRate)
            let quality = 0
            for (let i = 0; i < entries.length; i++) {
                let qRate: any = entries[i];
                let qQuality = qRate[0]
                let rate = qRate[1]
                if (rand.intn(max) <= rate) {
                    quality = Number(qQuality)
                    break
                } else {
                    max -= rate
                }
            }
            let items = gameConfig.items
            let tid = 172011
            let ids = []
            Object.entries(items).forEach(f => {
                let id: any = Number(f[0])
                let conf: any = f[1]
                if (conf && conf.equipmentKind && conf.equipmentKind == makeItemKind) {
                    ids.push(id)
                }
            })
            if (ids.length > 0) {
                tid = utils.getOneFromArray(ids, rand)
            }
            item = this.create(player, tid, makeItemLvl, rand, quality)
        } else {
            // 高级打造
            let max = 0, qualityRate = {}
            let highMakeQuality = gameConfig.town.makeConfig.highMakeQuality
            Object.entries(highMakeQuality).forEach(bmq => {
                let quaility = bmq[0]
                let rateValues = bmq[1] || [0, 0]
                let rate = utils.getIncValue(rateValues, lvl, true)
                max += rate
                qualityRate[quaility] = rate
            })

            let entries = Object.entries(qualityRate)
            let quality = 0
            for (let i = 0; i < entries.length; i++) {
                let qRate: any = entries[i];
                let qQuality = qRate[0]
                let rate = qRate[1]
                if (rand.intn(max) <= rate) {
                    quality = Number(qQuality)
                    break
                } else {
                    max -= rate
                }
            }
            let items = gameConfig.items
            let tid = 172011
            let ids = []
            Object.entries(items).forEach(f => {
                let id: any = Number(f[0])
                let conf: any = f[1]
                if (conf && conf.equipmentKind && conf.equipmentKind == makeItemKind) {
                    ids.push(id)
                }
            })
            if (ids.length > 0) {
                tid = utils.getOneFromArray(ids, rand)
            }
            item = this.create(player, tid, makeItemLvl, rand, quality, CreateKind.Boss)
        }
        return item
    }

    townCreate2(player: PlayerModel, data: any, rand) {
        let item: ItemModel = null, targetId = null
        let { makeItemLvl, makeItemKind, useItemNum, subItemKind, target, coe } = data
        let lvl = player.townInfo.subBuildLvl[TownBuildType.Make] || 0
        // 装备类型
        let subItemKinds
        if (makeItemKind == EquipmentItemType.Hand) {
            subItemKinds = {}
            Object.entries(gameConfig.items).filter(it => {
                let config: any = it[1]
                return config.equipmentKind == EquipmentItemType.Hand
            }).forEach(it => {
                let id = it[0]
                let config: any = it[1]
                subItemKinds[id] = config.name
            })
        } else {
            subItemKinds = {}
            Object.entries(gameConfig.items).filter(it => {
                let config: any = it[1]
                return config.equipmentKind == EquipmentItemType.SubHand
            }).forEach(it => {
                let id = it[0]
                let config: any = it[1]
                subItemKinds[id] = config.name
            })
        }
        // 高级打造
        let max = 0, qualityRate = {}
        let highMakeQuality = gameConfig.town.makeConfig.highMakeQuality
        Object.entries(highMakeQuality).filter(bmq => Number(bmq[0]) > 3).forEach(bmq => {
            let quaility: any = bmq[0]
            let rateValues = bmq[1] || [0, 0]
            let rate = utils.getIncValue(rateValues, lvl, true)
            let perRate = rate / 10
            let remainPerRate = (100 - rate) / 10
            if (useItemNum) {
                if (quaility != 6) {
                    rate -= perRate * useItemNum
                } else {
                    rate += remainPerRate * useItemNum
                }
            }
            if (rate < 0) {
                rate = 0
            } else if (rate > 100) {
                rate = 100
            }
            max += rate
            qualityRate[quaility] = rate
        })

        let entries = Object.entries(qualityRate)
        let quality = 0
        for (let i = 0; i < entries.length; i++) {
            let qRate: any = entries[i];
            let qQuality = qRate[0]
            let rate = qRate[1]
            if (rand.intn(max) <= rate) {
                quality = Number(qQuality)
                break
            } else {
                max -= rate
            }
        }
        let items = gameConfig.items
        let tid = 172011
        if (!subItemKind) {
            let ids = []
            Object.entries(items).forEach(f => {
                let id: any = Number(f[0])
                let conf: any = f[1]
                if (conf && conf.equipmentKind && conf.equipmentKind == makeItemKind) {
                    ids.push(id)
                }
            })
            if (ids.length > 0) {
                tid = utils.getOneFromArray(ids, rand)
            }
        } else if (subItemKind && target) {
            let rate = 5 * useItemNum
            if (rand.intn(100) <= rate) {
                tid = subItemKind
                targetId = target
            } else {
                let ids = []
                Object.entries(items).filter(f => Number(f[0]) != subItemKind).forEach(f => {
                    let id: any = Number(f[0])
                    let conf: any = f[1]
                    if (conf && conf.equipmentKind && conf.equipmentKind == makeItemKind) {
                        ids.push(id)
                    }
                })
                if (ids.length > 0) {
                    tid = utils.getOneFromArray(ids, rand)
                    let randItemConfig = gameConfigHandle.configByID[tid]
                    let roleID = utils.getOneFromArray(randItemConfig.targets || [], rand)
                    if (roleID == target) {
                        targetId = target
                    }
                }
            }
        } else {
            let rate = (100 / 15) * useItemNum
            if (rand.intn(100) <= rate) {
                tid = subItemKind
            } else {
                let ids = []
                Object.entries(items).filter(f => Number(f[0]) != subItemKind).forEach(f => {
                    let id: any = Number(f[0])
                    let conf: any = f[1]
                    if (conf && conf.equipmentKind && conf.equipmentKind == makeItemKind) {
                        ids.push(id)
                    }
                })
                if (ids.length > 0) {
                    tid = utils.getOneFromArray(ids, rand)
                }
            }
        }
        let skillID = null
        if (targetId) {
            let partnerConfig = gameConfigHandle.configByID[targetId]
            if (partnerConfig) {
                skillID = partnerConfig.skills[0]
            }
        }
        item = this.create(player, tid, makeItemLvl, rand, quality, CreateKind.Boss, null, skillID)

        return item
    }

    //一键穿装备
    oneKeyPutOnEquipments(player: PlayerModel, pIndex: number) {
        let partner = player.teamList.list[pIndex]
        let active = this.getEquipmentActive(player, partner)
        let equipmentsActive = partner.equipments[active]
        let equipmentBag = this.getEquipmentBag(player)
        let equips = equipmentBag.items
        let partList = gameConfigHandle.gameConfig.equipment.equipmentParts
        for (let i = 0; i < partList.length; i++) {
            let equipmentOn = equipmentsActive[partList[i]]
            let equipmentOnKind = equipmentHandle.equipmentPartToKind[partList[i]]
            let fcOn = this.getFcOfEquipment(equipmentOn)
            let have = false
            if (equipmentOn) {
                have = true
            }
            let bestEquip = null
            for (let j = 0; j < equips.length; j++) {
                let equip = equips[j]
                if (equip) {
                    let fcThis = this.getFcOfEquipment(equip)
                    if (fcThis > fcOn) {
                        let equipKind = gameConfigHandle.configByID[equip.tID].equipmentKind
                        if (equipmentOnKind == equipKind && partner.lvl >= equip.equipment.lvl) {
                            let partnerConfig = gameConfigHandle.configByID[partner.tID]
                            if (equipKind == EquipmentItemType.Hand || equipKind == EquipmentItemType.SubHand) {
                                let eqArr = equipKind == EquipmentItemType.Hand ? partnerConfig.mainHand : partnerConfig.subHand
                                let index = eqArr.findIndex(e => e == equip.tID)
                                if (index != -1) {
                                    bestEquip = equip
                                    fcOn = fcThis
                                }
                            } else {
                                bestEquip = equip
                                fcOn = fcThis
                            }
                        }
                    }
                }
            }
            if (bestEquip) {
                let res = true
                if (have) {
                    if (player.gameSet.autoEquipGem) {
                        let gems = []
                        for (let i = 0; i < equipmentOn.equipment.gems.length; i++) {
                            if (equipmentOn.equipment.gems[i]) {
                                gems.push(equipmentOn.equipment.gems[i])
                            }
                            equipmentOn.equipment.gems[i] = null
                        }
                        for (let i = 0; i < gems.length; i++) {
                            if (bestEquip.equipment.gems.length >= i + 1) {
                                if (bestEquip.equipment.gems[i]) {
                                    bagHandle.AddItemComponent(player.bag, bestEquip.equipment.gems[i])
                                }
                                bestEquip.equipment.gems[i] = gems[i]
                            } else {
                                if (player.gameSet.autoEquipHole) {
                                    let addHoleNeed = gameConfigHandle.gameConfig.equipment.addHoleNeed
                                    let needItemID = addHoleNeed[0]
                                    let needAmount = addHoleNeed[1]
                                    let haveAmount = bagHandle.getTotalNumByItemId(player.bag, needItemID)
                                    if (needAmount <= haveAmount) {
                                        bagHandle.removeItemByItemId(player.bag, needItemID, needAmount)
                                        bestEquip.equipment.gems[i] = gems[i]
                                    } else {
                                        bagHandle.AddItemComponent(player.bag, gems[i])
                                    }
                                } else {
                                    bagHandle.AddItemComponent(player.bag, gems[i])
                                }
                            }
                        }
                    }
                    res = bagHandle.AddItemComponent(equipmentBag, equipmentOn)
                }
                if (res) {
                    let pos = bestEquip.pos
                    bestEquip.new = 1
                    equipmentsActive[partList[i]] = bestEquip
                    bagHandle.removeItemByPosition(equipmentBag, pos)
                }
            }
        }
    }

    //计算装备评分
    getFcOfEquipment(equipment: ItemModel) {
        let fc = 0
        let fcOfAttrisConfig = gameConfigHandle.gameConfig.equipment.fcOfAttris
        if (equipment && equipment.equipment) {
            let attris = equipmentHandle.getAttriOfEquipment(equipment)
            for (let i = 0; i < equipment.equipment.mainAttris.length; i++) {
                let attri = equipment.equipment.mainAttris[i]
                let attriName = attri[0]
                let attriValue = attri[1]

                if (fcOfAttrisConfig[attriName]) {
                    fc += fcOfAttrisConfig[attriName] * attriValue
                }
            }
            //固定属性
            let fixedAttri = equipment.equipment.fixedAttri
            // fighterAttri[fixedAttri['name']] += fixedAttri['value']
            //随机属性
            let subAttris = equipment.equipment.subAttris
            let upPer = 0
            function hasOwnProperty(attriType) {
                let dist = ['reduceSkillCd', 'addSkillHurt', 'realHurt', 'antiRealHurt', 'reduceAttackHurt', 'reduceSkillHurt', 'bloodHp']
                return dist.includes(attriType)
            }
            for (let i = 0; i < subAttris.length; i++) {
                let attriType = subAttris[i][0]
                let attriNameOrSkillID = subAttris[i][1]
                let value = subAttris[i][2]
                if (attriType == 'attri') {
                    if (fcOfAttrisConfig[attriNameOrSkillID]) {
                        fc += fcOfAttrisConfig[attriNameOrSkillID] * value
                    }
                }
                else if (hasOwnProperty(attriType)) {
                    fc += fcOfAttrisConfig[attriType] * (value || attriNameOrSkillID);
                    upPer += value || attriNameOrSkillID
                }
            }
            fc *= (100 + upPer) / 100
            if (fc < 1) {
                fc = 1
            }
        }
        return Math.floor(fc)
    }

    //计算当前装备的总战力
    getEquipmentsOnTotalFc(player: PlayerModel, pIndex?: number) {
        let fc = 0
        player.teamList.list.forEach((p, i) => {
            if (p && (pIndex == null || pIndex == i)) {
                let equipmentsOn = p.equipments[p.equipmentActive] || []
                Object.entries(equipmentsOn).forEach(equipment => {
                    fc += this.getFcOfEquipment(equipment[1])
                })
            }
        })
        return fc
    }

    //获得星级星星
    getStars = (lvl) => {
        let stars = ''
        for (let i = 0; i < lvl; i++) {
            stars += '★'
        }
        return stars
    }

    //根据物品id 等级 创建模式生成宝物
    createTreasure(id: number, lvl: number, rand: Random, quality?: number, creatKind?: number) {
        creatKind = creatKind || 1  //默认为普通地图掉落模式
        let itemConfig = gameConfigHandle.configByID[id]
        let attriNames: string[] = itemConfig.attri
        let treasureItem = new TreasureItemModel()
        let coe = gameConfigHandle.gameConfig.map.coe
        //普通地图
        if (creatKind == 0) {
            let qualityDropNormal = gameConfigHandle.gameConfig.map.treasureQualityDropNormal
            treasureItem.quality = utils.getRandomValue(qualityDropNormal, coe, rand)
        }
        //精英地图
        else if (creatKind == 1) {
            let qualityDropElite = gameConfigHandle.gameConfig.map.treasureQualityDropElite
            treasureItem.quality = utils.getRandomValue(qualityDropElite, coe, rand)
        }
        //根据品级随机获得属性条数
        if (quality === undefined) {
            quality = treasureItem.quality
        } else {
            treasureItem.quality = quality
        }
        if (quality < 5 && quality > 2) {
            attriNames.splice(attriNames.indexOf(utils.getOneFromArray(attriNames, rand)), 1)
        } else if (quality <= 2) {
            attriNames = [utils.getOneFromArray(attriNames, rand)]
        }

        //根据品级生成主属性值
        let qualityUp = gameConfigHandle.gameConfig.equipment.qualityUp
        let mainAttriConfig = gameConfigHandle.gameConfig.equipment.treasureAttri
        let attriList = gameConfigHandle.gameConfig.partner.attriList
        let valueRandomRange = gameConfigHandle.gameConfig.equipment.valueRandomRange
        for (let i = 0; i < attriNames.length; i++) {
            let attriName = attriNames[i]
            let attriValue = utils.getIncValue(attriList[attriName], lvl * mainAttriConfig[attriName][0])
                * mainAttriConfig[attriName][1] * ((treasureItem.quality - 1) * qualityUp + 1)
            // attriValue = Math.floor(attriValue)
            let max = attriValue
            let min = Math.floor(attriValue * valueRandomRange[0] / 100)

            //creatKind=9 获得满值属性
            if (creatKind != 9) {
                attriValue = utils.addRandomByPer(attriValue, valueRandomRange[0], rand, 'float')
            }
            // attriValue = Math.floor(attriValue)
            attriValue = utils.getValueByAttri(attriValue, attriName)
            treasureItem.attris.push([attriName, attriValue])
        }
        treasureItem.lvl = lvl
        let item = itemHandle.create({ tID: id }, rand)
        item.treasure = treasureItem
        return item
    }

    //计算装备属性值
    getAttriOfEquipment(equipment: ItemModel) {
        if (!equipment) {
            return null
        }
        let attris = []
        //主属性
        let attrisJc = equipment.equipment.mainAttris
        let strengthenUp = gameConfigHandle.gameConfig.equipment.strengthenUp
        for (let i = 0; i < attrisJc.length; i++) {
            let attriName = attrisJc[i][0]
            let attriJc = attrisJc[i][1]
            let min = attrisJc[i][2]
            let max = attrisJc[i][3]
            let strengthen = equipment.equipment.strengthen
            let attriValue = attriJc * (1 + strengthenUp * strengthen)
            attriValue = utils.floor(attriValue, 2)
            if (strengthen == 0) {
                attris.push({ attriName, attriValue, min, max })
            }
            else {
                attris.push({ attriName, attriValue })
            }
        }
        return attris
    }

    //获取装备属性显示文本  包含换行符
    // getAttrisViewOfEquipment(equipment: ItemModel) {
    //     if (!equipment) {
    //         return null
    //     }
    //     let attrisView = ''
    //     //固定属性
    //     let fixedAttri = equipment.equipment.fixedAttri
    //     if (fixedAttri['name'] !== undefined) {
    //         attrisView += attriIcon[fixedAttri['name']] + ' ' + fieldText.attriText[fixedAttri['name']] + ': ' + fixedAttri['value'] + '&nbsp;&nbsp;&nbsp;[固定]<br />'
    //     }
    //     //主属性
    //     let attris = this.getAttriOfEquipment(equipment)
    //     attrisView += '---------------------------<br />'
    //     for (let i = 0; i < attris.length; i++) {
    //         if (attris[i].min) {
    //             attrisView += attriIcon[attris[i].attriName] + ' ' + fieldText.attriText[attris[i].attriName] + ': +' + attris[i].attriValue + '&nbsp;&nbsp;&nbsp;&nbsp;[' + attris[i].min + '&nbsp;-&nbsp;' + attris[i].max + ']' + '<br />'
    //         }
    //         else {
    //             attrisView += attriIcon[attris[i].attriName] + ' ' + fieldText.attriText[attris[i].attriName] + ': +' + attris[i].attriValue + '<br />'
    //         }
    //     }
    //     attrisView += '---------------------------'
    //     return attrisView
    // }

    getBackWhenSellItemOfStrengthen(item: ItemModel) {
        let usedProps: any[] = []
        if (item.equipment) {
            let strLvl = item.equipment.strengthen
            let lvl = item.equipment.lvl
            let needConfig = gameConfigHandle.gameConfig.equipment.equipmentStrNeed
            for (let i = strLvl - 1; i >= 0; i--) {
                usedProps = usedProps.concat(playerHandle.getNeed2(needConfig, i + lvl / 5))
            }
        }
        //把同种东西合并到一起
        let usedPropsIds: any[] = []
        let usedPropsAmounts: number[] = []
        for (let i = 0; i < usedProps.length; i++) {
            let item = usedProps[i]
            if (usedPropsIds.includes(item[0])) {
                usedPropsAmounts[usedPropsIds.indexOf(item[0])] += item[1]
            } else {
                usedPropsIds.push(item[0])
                usedPropsAmounts.push(item[1])
            }
        }
        let backPer = 100//返还比例
        backPer = gameConfigHandle.gameConfig.equipment.getBackPerWhenSellItemOfStr //按照配置百分比返还
        for (let i = 0; i < usedPropsAmounts.length; i++) {
            let value = usedPropsAmounts[i] * backPer / 100
            usedPropsAmounts[i] = Math.floor(value)
        }
        return { usedPropsIds, usedPropsAmounts }
    }

    //计算装备/宝物/傀儡的回收收益
    getPriceOfEquipment(equipment: ItemModel) {
        if (!equipment)
            return null
        if (equipment.equipment) {
            let equipmentConfig = gameConfigHandle.gameConfig.equipment
            let destroyGet = equipmentConfig.destroyGet
            let itemID = destroyGet.itemID
            let amount = utils.getIncValue(destroyGet.amount, equipment.equipment.quality)
            return { itemID, amount }
        }
    }

    //计算装备/宝物/傀儡的金币价值
    getMoneyPriceOfEquipment(equipment: ItemModel) {
        if (!equipment) {
            return null
        }
        let price = 0
        let priceJc = gameConfigHandle.configByID[equipment.tID].price
        if (equipment.equipment) {
            let lvl = equipment.equipment.lvl
            let quality = equipment.equipment.quality
            let strengthen = equipment.equipment.strengthen
            price = utils.getIncValue(priceJc, lvl - 1) * (1 + 0.2 * (quality - 1)) * (1 + 0.2 * strengthen)
        }
        else if (equipment.treasure) {
            let lvl = equipment.treasure.lvl
            let quality = equipment.treasure.quality
            price = utils.getIncValue(priceJc, lvl - 1) * (1 + 0.2 * (quality - 1))
        }
        price = Math.floor(price)
        return price
    }

    //计算回收装备可以获得的魂晶
    getGoldPriceOfEquipment(equipment: ItemModel) {
        if (!equipment) {
            return null
        }
        let price = 0
        if (equipment.equipment) {
            let lvl = equipment.equipment.lvl
            let priceJc = Math.floor(lvl / 10) + 1
            let quality = equipment.equipment.quality
            if (quality < 5) {
                return 0
            }
            let strengthen = equipment.equipment.strengthen
            let strUp = 1
            if (strengthen == 10)//强化10  价格6倍
                strUp = 6
            else if (strengthen == 9)//强化9  价格4倍
                strUp = 4
            else if (strengthen == 8)//强化8  价格2倍
                strUp = 2

            price = priceJc * strUp
            if (quality == 6) {
                price *= 2
            }
        }
        else if (equipment.treasure) {
            let quality = equipment.treasure.quality
            if (quality < 5) {
                return 0
            }
            let lvl = equipment.treasure.lvl
            price = Math.floor(lvl / 10) + 1
            if (quality == 6) {
                price *= 2
            }
        }
        return price
    }

    //装备属性计算
    calcEquipment(partner: PartnerModel,) {
        let fighter: FighterModel = new FighterModel()
        fighter.attri = new FighterAttriModel()
        let equipments = partner.equipments[partner.equipmentActive]
        gameConfigHandle.gameConfig.equipment.equipmentParts.forEach(part => {
            let equipment: ItemModel = equipments[part]
            if (equipment) {
                //主属性
                let attris = equipmentHandle.getAttriOfEquipment(equipment)
                for (let i = 0; i < attris.length; i++) {
                    if (!fighter.attri[attris[i].attriName]) {
                        fighter.attri[attris[i].attriName] = 0
                    }
                    fighter.attri[attris[i].attriName] += attris[i].attriValue
                }
                //固定属性
                let fixedAttri = equipment.equipment.fixedAttri
                fixedAttri.forEach(item => {
                    fighter.attri[item[0]] += item[1]
                })

                //镶嵌的宝石属性
                let gems = equipment.equipment.gems
                if (gems) {
                    for (let i = 0; i < gems.length; i++) {
                        let gem = gems[i]
                        if (gem != null) {
                            let equipmentKind = gameConfigHandle.configByID[equipment.tID].equipmentKind
                            let part = this.equipmentKindToPart[equipmentKind]
                            let attri = this.getGemAttriOfPart(gem.tID, gem.hp, part)
                            fighter.attri[attri.attriName] += attri.attriValue
                        }
                    }
                }
                //随机属性
                let subAttris = equipment.equipment.subAttris
                for (let i = 0; i < subAttris.length; i++) {
                    let attriType = subAttris[i][0]
                    let attriNameOrSkillID = subAttris[i][1]
                    let value = subAttris[i][2]
                    if (attriType == 'attri') {
                        fighter.attri[attriNameOrSkillID] += value
                    } else if (attriType == 'reduceSkillCd') {
                        if (!fighter.skillsReduceCd[attriNameOrSkillID]) {
                            fighter.skillsReduceCd[attriNameOrSkillID] = 0
                        }
                        fighter.skillsReduceCd[attriNameOrSkillID] += value
                    } else if (attriType == 'addSkillHurt') {
                        if (!fighter.skillsHurtPer[attriNameOrSkillID]) {
                            fighter.skillsHurtPer[attriNameOrSkillID] = 0
                        }
                        fighter.skillsHurtPer[attriNameOrSkillID] += value
                    } else if (attriType == 'statusHurtPer') {
                        if (!fighter.statusHurtPer[attriNameOrSkillID]) {
                            fighter.statusHurtPer[attriNameOrSkillID] = 0
                        }
                        fighter.statusHurtPer[attriNameOrSkillID] += value
                    } else if (attriType == 'statusReduceHurt') {
                        if (!fighter.statusReduceHurt[attriNameOrSkillID]) {
                            fighter.statusReduceHurt[attriNameOrSkillID] = 0
                        }
                        fighter.statusReduceHurt[attriNameOrSkillID] += value
                    }
                }
            }
        })
        return fighter
    }

    //获取宝石镶嵌在指定部位的属性值
    getGemAttriOfPart(tID: number, gemLvl: number, part: string) {
        gemLvl -= 1
        let attriList = gameConfigHandle.gameConfig.partner.attriList
        let gemConfig = gameConfigHandle.configByID[tID]
        let gemAttrisConfig = gameConfigHandle.gameConfig.gem.attris[gemConfig.gemType]
        if (!gemAttrisConfig) {
            return { attriName: 0, attriValue: 0 }
        }
        let attrisConfig = gemAttrisConfig[part]
        let attriName = attrisConfig.attri
        let values = attrisConfig.values
        let upValues = attriList[attriName]
        let attriValue = utils.getIncValue(upValues, (gemLvl + 1) * values[0]) * values[1]
        let lvl = (gemLvl + 1)
        attriValue = attriValue + (values[1] || 0) * lvl * (lvl + 1)
        let isPer = utils.getPerByAttri(attriName) == '%'
        if (isPer) {
            attriValue = Number(attriValue.toFixed(1))
        }
        return { attriName, attriValue }
    }

    getEquipmentActive (playerModel: PlayerModel, partner: PartnerModel) {
        let gameMode = playerModel.gameSet.gameMode
        let equipmentActive = partner.equipmentActive
        if (gameMode) {
            equipmentActive = 1
        }
        return equipmentActive
    }

    getEquipmentBag (playerModel: PlayerModel) {
        let gameMode = playerModel.gameSet.gameMode
        let equipmentBag = playerModel.equipmentBag
        if (gameMode) {
            equipmentBag = playerModel.equipmentBag2
        }
        return equipmentBag
    
    }
}


let equipmentHandle = new EquipmentHandle()

export default equipmentHandle;